#include "formgroup.h"
#include "ui_formgroup.h"

FormGroup::FormGroup(QSqlDatabase db, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormGroup),
    dbase(db),
    modelGroup(new QSqlTableModel(this,dbase))
{
    ui->setupUi(this);

    ui->tableView->setContextMenuPolicy(Qt::ActionsContextMenu);
    ui->tableView->addAction(ui->actionAddGroup);
    ui->actionAddGroup->setIcon(QIcon::fromTheme("user-group-new"));
    ui->tableView->addAction(ui->actionDelete_group);
    ui->actionDelete_group->setIcon(QIcon::fromTheme("user-group-delete"));
    ui->tableView->setSelectionBehavior(QTableView::SelectRows);
    ui->tableView->setSelectionMode(QTableView::SingleSelection);
    modelGroup->setEditStrategy(QSqlTableModel::OnRowChange);
}

FormGroup::~FormGroup()
{
    delete ui;
}

void FormGroup::on_actionAddGroup_triggered()
{
    modelGroup->submitAll();
    modelGroup->insertRow(modelGroup->rowCount());
    modelGroup->setData(modelGroup->index(modelGroup->rowCount()-1, 1), tr("Group name"));
    modelGroup->setData(modelGroup->index(modelGroup->rowCount()-1, 2), tr("m"));
    modelGroup->setData(modelGroup->index(modelGroup->rowCount()-1, 3), 4);
    modelGroup->setData(modelGroup->index(modelGroup->rowCount()-1, 4), 7);
}

void FormGroup::on_actionDelete_group_triggered()
{
    if (ui->tableView->currentIndex().isValid()) modelGroup->removeRow(ui->tableView->currentIndex().row());
}

void FormGroup::showEvent(QShowEvent *e)
{
    modelGroup->setTable("group");
    ui->tableView->setModel(modelGroup);
    ui->tableView->hideColumn(0);
    modelGroup->setHeaderData(1, Qt::Horizontal, tr("Group"));
    modelGroup->setHeaderData(2, Qt::Horizontal, tr("gender"));
    modelGroup->setHeaderData(3 ,Qt::Horizontal, tr("age min"));
    modelGroup->setHeaderData(4 ,Qt::Horizontal, tr("age max"));
    modelGroup->select();
    ui->tableView->show();
    e->accept();
}
